package com.xsm.ppsecret.ui.ease;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.exceptions.HyphenateException;
import com.jaeger.library.StatusBarUtil;
import com.xsm.ppsecret.R;
import com.xsm.ppsecret.util.ShareManager;
import com.xsm.ppsecret.util.UiSetting;
import com.xsm.ppsecret.widgets.FindUserDialog;
import com.xsm.ppsecret.widgets.RegisterEaseDialog;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChatListActivity extends AppCompatActivity implements RegisterEaseDialog.RegistListener, View.OnClickListener, FindUserDialog.FindUserListener {

    private EaseConversationListFragment conversationListFragment;
    private static final int REGISTER_OK = 521;
    private static final int REGISTER_ERROR = 522;
    @BindView(R.id.menu_normal_title)
    TextView menuTitle;
    @BindView(R.id.menu_normal_action)
    TextView menuAction;
    @BindView(R.id.ll_not_regist)
    LinearLayout registLayout;
    @BindView(R.id.et_username)
    EditText username;
    @BindView(R.id.tv_regist_confirm)
    TextView confirm;

    private MyHandler mHandler = new MyHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_list);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.appColor), 0);
        UiSetting.setStatusBarDarkModel(this);
        ButterKnife.bind(this);
        menuTitle.setText("会话列表");
        menuAction.setText("找人");
        menuAction.setOnClickListener(this);
        confirm.setOnClickListener(this);
        conversationListFragment = new EaseConversationListFragment();
        conversationListFragment.setConversationListItemClickListener(new EaseConversationListFragment.EaseConversationListItemClickListener() {

            @Override
            public void onListItemClicked(EMConversation conversation) {
                Intent intent = new Intent(ChatListActivity.this, ChatActivity.class);
                intent.putExtra("userId", conversation.conversationId());
                startActivity(intent);
            }
        });
        getSupportFragmentManager().beginTransaction().add(R.id.activity_chat_list, conversationListFragment).commit();

        if (ShareManager.getInstance().isFirstUseChat()) {
            registLayout.setVisibility(View.VISIBLE);
        } else {
            registLayout.setVisibility(View.GONE);
        }

    }

    @Override
    public void regist(final String username) {
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "用户名为空，请重新注册", Toast.LENGTH_SHORT).show();
            return;
        }
        final ShareManager shareManager = ShareManager.getInstance();
        shareManager.setUsername(username);
        new Thread() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(username, username);
                    mHandler.sendEmptyMessage(REGISTER_OK);
                    shareManager.setNotFirstUseChat();
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    Message message = mHandler.obtainMessage(REGISTER_ERROR);
                    mHandler.sendMessage(message);
                }
            }
        }.start();
    }

    private void loginEM() {
        ShareManager shareManager = ShareManager.getInstance();
        EMClient.getInstance().login(shareManager.getUsername(), shareManager.getPassword(), new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient emClient = EMClient.getInstance();
                emClient.groupManager().loadAllGroups();
                emClient.chatManager().loadAllConversations();
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_regist_confirm:
                String string = username.getText().toString();
                regist(string);
                break;
            case R.id.menu_normal_action:
                FindUserDialog findUserDialog = new FindUserDialog(this, R.style.customDialogStyle, this);
                findUserDialog.show();
                break;

        }

    }

    @Override
    public void find(String username) {
        if (!TextUtils.isEmpty(username)) {
            Intent intent = new Intent(this, ChatActivity.class);
            intent.putExtra("userId", username);
            startActivity(intent);
        }
    }

    @OnClick(R.id.menu_normal_back) void back() {
        finish();
    }

    private static class MyHandler extends Handler {

        WeakReference<Activity> mWeakReference;

        public MyHandler(Activity activity) {
            mWeakReference = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final Activity activity = mWeakReference.get();
            if(activity != null) {
                switch (msg.what) {
                    case REGISTER_OK:
                        if (activity instanceof ChatListActivity) {
                            ChatListActivity listActivity = (ChatListActivity) activity;
                            listActivity.loginEM();
                            ShareManager.getInstance().setNotFirstUseChat();
                            Toast.makeText(listActivity, "注册成功", Toast.LENGTH_SHORT).show();
                            listActivity.registLayout.setVisibility(View.GONE);
                        }
                        break;
                    case REGISTER_ERROR:
                        if (activity instanceof ChatListActivity) {
                            ChatListActivity chatListActivity = (ChatListActivity) activity;
                            Toast.makeText(chatListActivity, "注册失败，可能是用户名已存在，请您重新注册", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        }
    }

}
